<!-- build time:Wed Feb 20 2019 22:47:05 GMT+0800 (中国标准时间) --><!DOCTYPE html><html class="theme-next mist use-motion" lang="zh-CN"><head><meta name="generator" content="Hexo 3.8.0"><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=2"><meta name="theme-color" content="#222"><script src="//cdnjs.cloudflare.com/ajax/libs/pace/1.0.2/pace.min.js"></script><link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/pace/1.0.2/themes/blue/pace-theme-minimal.min.css"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><link rel="stylesheet" href="https://fonts.cat.net/css?family=Lato:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Cookie:300,300italic,400,400italic,700,700italic|Roboto Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext"><link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.2/css/font-awesome.min.css"><link rel="stylesheet" href="/alex.d-blog/css/main.css?v=7.0.0"><link rel="apple-touch-icon" sizes="180x180" href="/alex.d-blog/images/logo-180x180.jpg?v=7.0.0"><link rel="icon" type="image/png" sizes="32x32" href="/alex.d-blog/images/favicon-32x32.ico?v=7.0.0"><link rel="icon" type="image/png" sizes="16x16" href="/alex.d-blog/images/favicon-16x16.ico?v=7.0.0"><link rel="mask-icon" href="/alex.d-blog/images/logo.svg?v=7.0.0" color="#222"><script id="hexo.configurations">var NexT=window.NexT||{},CONFIG={root:"/alex.d-blog/",scheme:"Mist",version:"7.0.0",sidebar:{position:"left",width:320,display:"hide",offset:12,b2t:!1,scrollpercent:!0,onmobile:!0},fancybox:!1,fastclick:!1,lazyload:!1,tabs:!0,motion:{enable:!0,async:!0,transition:{post_block:"fadeIn",post_header:"slideDownIn",post_body:"slideDownIn",coll_header:"slideLeftIn",sidebar:"slideUpIn"}},algolia:{applicationID:"",apiKey:"",indexName:"",hits:{per_page:10},labels:{input_placeholder:"Search for Posts",hits_empty:"We didn't find any results for the search: ${query}",hits_stats:"${hits} results found in ${time} ms"}}}</script><script>!function(e,t,o,c,i,a,n){e.DaoVoiceObject=i,e[i]=e[i]||function(){(e[i].q=e[i].q||[]).push(arguments)},e[i].l=1*new Date,a=t.createElement(o),n=t.getElementsByTagName(o)[0],a.async=1,a.src=c,a.charset="utf-8",n.parentNode.insertBefore(a,n)}(window,document,"script",("https:"==document.location.protocol?"https:":"http:")+"//widget.daovoice.io/widget/0f81ff2f.js","daovoice"),daovoice("init",{app_id:"50185433"}),daovoice("update")</script><meta name="description" content="简单记录学习Python中，对于函数编程及高级函数、闭包等内容。"><meta name="keywords" content="Python,函数式编程,高阶函数,闭包"><meta property="og:type" content="article"><meta property="og:title" content="Python学习笔记 - 函数式编程之高阶函数"><meta property="og:url" content="https://alex_d.gitee.io/alex.d-blog/posts/736330a0/index.html"><meta property="og:site_name" content="Alex.D&#39;s Bolg"><meta property="og:description" content="简单记录学习Python中，对于函数编程及高级函数、闭包等内容。"><meta property="og:locale" content="zh-CN"><meta property="og:updated_time" content="2018-12-10T08:27:29.081Z"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="Python学习笔记 - 函数式编程之高阶函数"><meta name="twitter:description" content="简单记录学习Python中，对于函数编程及高级函数、闭包等内容。"><link rel="alternate" href="/alex.d-blog/rss.xml" title="Alex.D's Bolg" type="application/atom+xml"><link rel="canonical" href="https://alex_d.gitee.io/alex.d-blog/posts/736330a0/"><script id="page.configurations">CONFIG.page={sidebar:""}</script><title>Python学习笔记 - 函数式编程之高阶函数 | Alex.D's Bolg</title><script>var _hmt=_hmt||[];!function(){var e=document.createElement("script");e.src="https://hm.baidu.com/hm.js?a85d91dd2c37292e1961b5b4f63dc986";var t=document.getElementsByTagName("script")[0];t.parentNode.insertBefore(e,t)}()</script><noscript><style>.sidebar-inner,.use-motion .brand,.use-motion .collection-title,.use-motion .comments,.use-motion .menu-item,.use-motion .motion-element,.use-motion .pagination,.use-motion .post-block,.use-motion .post-body,.use-motion .post-header{opacity:initial}.use-motion .logo,.use-motion .site-subtitle,.use-motion .site-title{opacity:initial;top:initial}.use-motion .logo-line-before i{left:initial}.use-motion .logo-line-after i{right:initial}</style></noscript></head><body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN"><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><div class="custom-logo-site-title"><a href="/alex.d-blog/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title">Alex.D's Bolg</span> <span class="logo-line-after"><i></i></span></a></div><h1 class="site-subtitle" itemprop="description">Don't trouble trouble until trouble troubles you.</h1></div><div class="site-nav-toggle"><button aria-label="切换导航栏"><span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span></button></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/alex.d-blog/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i><br>首页</a></li><li class="menu-item menu-item-tags"><a href="/alex.d-blog/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i><br>标签<span class="badge">49</span></a></li><li class="menu-item menu-item-categories"><a href="/alex.d-blog/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i><br>分类<span class="badge">19</span></a></li><li class="menu-item menu-item-archives"><a href="/alex.d-blog/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i><br>归档<span class="badge">32</span></a></li><li class="menu-item menu-item-about"><a href="/alex.d-blog/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i><br>关于</a></li><li class="menu-item menu-item-commonweal"><a href="/alex.d-blog/404/" rel="section"><i class="menu-item-icon fa fa-fw fa-heartbeat"></i><br>公益 404</a></li><li class="menu-item menu-item-search"><a href="javascript:;" class="popup-trigger"><i class="menu-item-icon fa fa-search fa-fw"></i><br>搜索</a></li></ul><div class="site-search"><div class="popup search-popup local-search-popup"><div class="local-search-header clearfix"><span class="search-icon"><i class="fa fa-search"></i> </span><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span><div class="local-search-input-wrapper"><input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input"></div></div><div id="local-search-result"></div></div></div></nav></div></header><span class="exturl github-corner" data-url="aHR0cHM6Ly9naXRodWIuY29tL2FueWVy" title="Follow me on GitHub" aria-label="Follow me on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#222;color:#fff;position:absolute;top:0;border:0;right:0" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin:130px 106px" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></span><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"><div class="post-block"><link itemprop="mainEntityOfPage" href="https://alex_d.gitee.io/alex.d-blog/alex.d-blog/posts/736330a0/"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="name" content="Alex.D"><meta itemprop="description" content="Alex.D 个人博客，记录和分享工作经验、学习心得等"><meta itemprop="image" content="/alex.d-blog/images/avatar.jpg"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="Alex.D's Bolg"></span><header class="post-header"><h2 class="post-title" itemprop="name headline">Python学习笔记 - 函数式编程之高阶函数</h2><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i> </span><span class="post-meta-item-text">发表于</span> <time title="创建时间：2018-12-06 10:54:57" itemprop="dateCreated datePublished" datetime="2018-12-06T10:54:57+08:00">2018-12-06</time> <span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-calendar-check-o"></i> </span><span class="post-meta-item-text">更新于</span> <time title="修改时间：2018-12-10 16:27:29" itemprop="dateModified" datetime="2018-12-10T16:27:29+08:00">2018-12-10</time> </span><span class="post-category"><span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-folder-o"></i> </span><span class="post-meta-item-text">分类于</span> <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/alex.d-blog/categories/Python/" itemprop="url" rel="index"><span itemprop="name">Python</span></a></span> ， <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/alex.d-blog/categories/Python/函数式编程/" itemprop="url" rel="index"><span itemprop="name">函数式编程</span></a></span> </span><span class="post-comments-count"><span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-comment-o"></i> </span><span class="post-meta-item-text">评论数：</span> <a href="/alex.d-blog/posts/736330a0/#comments" itemprop="discussionUrl"><span class="post-comments-count valine-comment-count" data-xid="/alex.d-blog/posts/736330a0/" itemprop="commentCount"></span> </a></span><span id="/alex.d-blog/posts/736330a0/" class="leancloud_visitors" data-flag-title="Python学习笔记 - 函数式编程之高阶函数"><span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-eye"></i> </span><span class="post-meta-item-text">阅读次数：</span> <span class="leancloud-visitors-count"></span></span><div class="post-symbolscount"><span class="post-meta-item-icon"><i class="fa fa-file-word-o"></i> </span><span class="post-meta-item-text">本文字数：</span> <span title="本文字数">7.5k</span> <span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-clock-o"></i> </span><span class="post-meta-item-text">阅读时长 &asymp;</span> <span title="阅读时长">7 分钟</span></div><div class="post-description">简单记录学习Python中，对于函数编程及高级函数、闭包等内容。</div></div></header><div class="post-body" itemprop="articleBody"><h2 id="函数式编程"><a href="#函数式编程" class="headerlink" title="函数式编程"></a>函数式编程</h2><blockquote><p>函数式编程（Functional Programming），是一种抽象程度很高的编程范式，纯粹的函数式编程语言编写的函数没有变量。因此，任意一个函数，只要输入是确定的，输出就是确定的。</p><p>函数式编程是一种<span class="exturl" data-url="aHR0cDovL2VuLndpa2lwZWRpYS5vcmcvd2lraS9Qcm9ncmFtbWluZ19wYXJhZGlnbQ==" title="http://en.wikipedia.org/wiki/Programming_paradigm">“编程范式”<i class="fa fa-external-link"></i></span>（programming paradigm）。它属于<span class="exturl" data-url="aHR0cDovL2VuLndpa2lwZWRpYS5vcmcvd2lraS9TdHJ1Y3R1cmVkX3Byb2dyYW1taW5n" title="http://en.wikipedia.org/wiki/Structured_programming">“结构化编程”<i class="fa fa-external-link"></i></span>的一种，主要思想是把运算过程尽量写成一系列嵌套的函数调用。</p><p>函数式编程的一个特点就是，允许把函数本身作为参数传入另一个函数，还允许返回一个函数！Python对函数式编程提供部分支持。由于Python允许使用变量，因此，Python不是纯函数式编程语言。</p></blockquote><p>更多内容</p><ul><li><span class="exturl" data-url="aHR0cHM6Ly93d3cubGlhb3h1ZWZlbmcuY29tL3dpa2kvMDAxNDMxNjA4OTU1NzI2NGE2YjM0ODk1OGY0NDk5NDlkZjQyYTZkM2EyZTU0MmMwMDAvMDAxNDMxNzg0ODQyODEyNWFlNmFhMjQwNjhiNGM1MGE3ZTcxNTAxYWIyNzVkNTIwMDA=" title="https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317848428125ae6aa24068b4c50a7e71501ab275d52000">廖雪峰Python教程 函数式编程<i class="fa fa-external-link"></i></span></li><li><span class="exturl" data-url="aHR0cDovL3d3dy5ydWFueWlmZW5nLmNvbS9ibG9nLzIwMTIvMDQvZnVuY3Rpb25hbF9wcm9ncmFtbWluZy5odG1s" title="http://www.ruanyifeng.com/blog/2012/04/functional_programming.html">函数式编程初探 - 阮一峰<i class="fa fa-external-link"></i></span></li><li><span class="exturl" data-url="aHR0cHM6Ly93d3cua2FuY2xvdWQuY24va2FuY2xvdWQvZnVuY3Rpb25hbC1wcm9ncmFtbS1mb3ItcmVzdC81NjkzMw==" title="https://www.kancloud.cn/kancloud/functional-programm-for-rest/56933">函数式编程 - 看云<i class="fa fa-external-link"></i></span></li><li><span class="exturl" data-url="aHR0cHM6Ly9iYWlrZS5iYWlkdS5jb20vaXRlbS8lRTUlODclQkQlRTYlOTUlQjAlRTUlQkMlOEYlRTclQkMlOTYlRTclQTglOEI=" title="https://baike.baidu.com/item/%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B">函数式编程 - 百度百科<i class="fa fa-external-link"></i></span></li></ul><hr><h3 id="高阶函数"><a href="#高阶函数" class="headerlink" title="高阶函数"></a>高阶函数</h3><p>函数式编程中，可以将函数当作变量一样使用。接受函数为参数，或者把函数作为结果返回的函数称为<strong>高阶函数（Higher-order Functions）</strong> 。</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">double</span><span class="params">(x)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">2</span> * x</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">square</span><span class="params">(x)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> x * x</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">func</span><span class="params">(g, arr)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> [g(x) <span class="keyword">for</span> x <span class="keyword">in</span> arr]</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>arr1 = func(double, [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>])</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>arr2 = func(square, [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>])</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>arr1</span><br><span class="line">[<span class="number">2</span>, <span class="number">4</span>, <span class="number">6</span>, <span class="number">8</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>arr2</span><br><span class="line">[<span class="number">1</span>, <span class="number">4</span>, <span class="number">9</span>, <span class="number">16</span>]</span><br></pre></td></tr></table></figure><p><strong>map()</strong>/<strong>reduce()</strong>/<strong>filter()</strong>/<strong>sorted()</strong> /<strong>apply()</strong> 是 Python 中较为常用的高阶函数，它们为函数式编程提供了不少便利。</p><p>Python 3 中，<code>map</code> 和 <code>filter</code> 还是内置函数，但是由于引入了列表推导和生成器表达式，它们变得没那么重要了。列表推导或生成器表达式具有 <code>map</code> 和 <code>filter</code> 两个函数的功能，而且更易于阅读。<code>apply</code> 函数在Python 2.3 中标记为过时，在Python 3 中移除了，因为不再需要它了。如果想使用不定量的参数调用函数，可以编写 <code>fn(*args, **keywords)</code>，不用再编写 <code>apply(fn, args,kwargs)</code>。</p><hr><h4 id="map"><a href="#map" class="headerlink" title="map()"></a>map()</h4><p><code>map</code> 函数将传入的函数依次作用到序列的每个元素，并把结果作为新的 <code>Iterator</code> 返回。<code>map</code> 函数语法：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># map(function, iterable, ...)</span></span><br><span class="line"><span class="comment">## 参数 —— function : 函数 ;  iterable : 一个或多个序列</span></span><br><span class="line"><span class="comment">## 返回值 —— Python 2.x 返回列表； Python 3.x 返回迭代器（map）</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">square</span><span class="params">(x)</span>:</span>		<span class="comment"># 计算平方数</span></span><br><span class="line">    <span class="keyword">return</span> x ** <span class="number">2</span></span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>map(square, [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>])   <span class="comment"># 计算列表各个元素的平方</span></span><br><span class="line">&lt;map object at <span class="number">0x000001B9F81ADEB8</span>&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>map(<span class="keyword">lambda</span> x: x ** <span class="number">2</span>, [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>])  <span class="comment"># 使用 lambda 匿名函数</span></span><br><span class="line"><span class="comment"># [1, 4, 9, 16, 25]			  		 # python2输出结果</span></span><br><span class="line">&lt;map object at <span class="number">0x000001B9F81ADEB8</span>&gt;    <span class="comment"># python3输出结果（可使用list()函数对map函数返回结果进行转换）</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>list(map(<span class="keyword">lambda</span> x: x ** <span class="number">2</span>, [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>]))</span><br><span class="line">[<span class="number">1</span>, <span class="number">4</span>, <span class="number">9</span>, <span class="number">16</span>, <span class="number">25</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># map实现list的值的格式批量转换</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>list(map(str, [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>]))</span><br><span class="line">[<span class="string">'1'</span>, <span class="string">'2'</span>, <span class="string">'3'</span>, <span class="string">'4'</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>list(map(int, [<span class="string">'1'</span>, <span class="string">'2'</span>, <span class="string">'3'</span>, <span class="string">'4'</span>]))</span><br><span class="line">[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 提供了两个列表，对相同位置的列表数据进行相加</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>map(<span class="keyword">lambda</span> x, y: x + y, [<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">9</span>], [<span class="number">2</span>, <span class="number">4</span>, <span class="number">6</span>, <span class="number">8</span>, <span class="number">10</span>])</span><br><span class="line">[<span class="number">3</span>, <span class="number">7</span>, <span class="number">11</span>, <span class="number">15</span>, <span class="number">19</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># -------- 列表推导式实现上述功能 -----------</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>[square(n) <span class="keyword">for</span> n <span class="keyword">in</span> [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>]]</span><br><span class="line">[<span class="number">1</span>, <span class="number">4</span>, <span class="number">9</span>, <span class="number">16</span>, <span class="number">25</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>[str(n) <span class="keyword">for</span> n <span class="keyword">in</span> [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>]]</span><br><span class="line">[<span class="string">'1'</span>, <span class="string">'2'</span>, <span class="string">'3'</span>, <span class="string">'4'</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>[int(n) <span class="keyword">for</span> n <span class="keyword">in</span> [<span class="string">'1'</span>, <span class="string">'2'</span>, <span class="string">'3'</span>, <span class="string">'4'</span>]]</span><br><span class="line">[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>]</span><br></pre></td></tr></table></figure><hr><h4 id="reduce"><a href="#reduce" class="headerlink" title="reduce()"></a>reduce()</h4><p><code>reduce()</code> 函数会对参数序列中元素进行累积。函数将一个数据集合（链表，元组等）中的所有数据进行下列操作：用传给 <code>reduce()</code> 中的函数 <code>function</code>（有两个参数）先对集合中的第 1、2 个元素进行操作，得到的结果后继续和序列的下一个元素做累积计算，直到累积到列表最后一个数据。Python 2 中，reduce 是内置函数，但是在Python 3 中放到functools 模块里了。<code>reduce()</code> 函数语法：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># reduce(function, iterable[, initializer])</span></span><br><span class="line"><span class="comment">## 参数 —— function：函数，有两个参数； iterable ： 可迭代对象； initializer：可选，初始参数</span></span><br><span class="line"><span class="comment">## 返回值 —— 返回函数计算结果。</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 序列求和实现</span></span><br><span class="line"><span class="keyword">from</span> functools <span class="keyword">import</span> reduce	<span class="comment"># Python3 需要引入</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add</span><span class="params">(x, y)</span> :</span>            <span class="comment"># 两数相加（或使用 from operator import add）</span></span><br><span class="line">	<span class="keyword">return</span> x + y</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>reduce(add, [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>])   <span class="comment"># 计算列表和：1+2+3+4+5</span></span><br><span class="line"><span class="number">15</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>reduce(<span class="keyword">lambda</span> x, y: x * y, [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>])  <span class="comment"># 相当于 ((1 * 2) * 3) * 4</span></span><br><span class="line"><span class="number">24</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>reduce(<span class="keyword">lambda</span> x, y: x * y, [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>], <span class="number">5</span>) <span class="comment"># ((((5 * 1) * 2) * 3)) * 4</span></span><br><span class="line"><span class="number">120</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>reduce(<span class="keyword">lambda</span> x, y: x / y, [<span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>], <span class="number">72</span>)  <span class="comment">#  (((72 / 2) / 3)) / 4</span></span><br><span class="line"><span class="number">3</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>reduce(<span class="keyword">lambda</span> x, y: x + y, [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>], <span class="number">5</span>)  <span class="comment"># ((((5 + 1) + 2) + 3)) + 4</span></span><br><span class="line"><span class="number">15</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>reduce(<span class="keyword">lambda</span> x, y: x - y, [<span class="number">8</span>, <span class="number">5</span>, <span class="number">1</span>], <span class="number">20</span>)  <span class="comment"># ((20 - 8) - 5) - 1</span></span><br><span class="line"><span class="number">6</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>f = <span class="keyword">lambda</span> a, b: a <span class="keyword">if</span> (a &gt; b) <span class="keyword">else</span> b   <span class="comment"># 两两比较，取最大值</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>reduce(f, [<span class="number">5</span>, <span class="number">8</span>, <span class="number">1</span>, <span class="number">10</span>])</span><br><span class="line"><span class="number">10</span></span><br></pre></td></tr></table></figure><p><strong>注意：</strong> 在 Python3 中，reduce() 函数已经被从全局名字空间里移除了，它现在被放置在 fucntools 模块里，如果想要使用它，则需要通过引入 functools 模块来调用 reduce() 函数：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> functools <span class="keyword">import</span> reduce</span><br></pre></td></tr></table></figure><hr><h4 id="filter"><a href="#filter" class="headerlink" title="filter()"></a>filter()</h4><p><strong>filter()</strong> 函数用于过滤序列，过滤掉不符合条件的元素，Python2返回过滤后的列表，Python3返回迭代器对象（filter），如果要转换为列表，可以使用 list() 来转换。</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># filter(function, iterable)</span></span><br><span class="line"><span class="comment">## 参数 —— function : 判断函数; iterable : 可迭代对象</span></span><br><span class="line"><span class="comment">## 返回值 —— 返回一个迭代器对象</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 过滤出列表中的所有奇数</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">is_odd</span><span class="params">(n)</span> :</span></span><br><span class="line">    <span class="keyword">return</span> n % <span class="number">2</span> == <span class="number">1</span></span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>list(filter(is_odd, [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, <span class="number">8</span>, <span class="number">9</span>, <span class="number">10</span>]))</span><br><span class="line">[<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">9</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 过滤出1~100中平方根是整数的数</span></span><br><span class="line"><span class="keyword">import</span> math</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">is_sqr</span><span class="params">(n)</span> :</span></span><br><span class="line">	<span class="keyword">return</span> math.sqrt(n) % <span class="number">1</span> == <span class="number">0</span></span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>list(filter(is_sqr, range(<span class="number">1</span>, <span class="number">101</span>)))</span><br><span class="line">[<span class="number">1</span>, <span class="number">4</span>, <span class="number">9</span>, <span class="number">16</span>, <span class="number">25</span>, <span class="number">36</span>, <span class="number">49</span>, <span class="number">64</span>, <span class="number">81</span>, <span class="number">100</span>]</span><br></pre></td></tr></table></figure><p><strong>注意：</strong>Python3 中返回到是一个 <code>filter</code> 类，<code>filter</code> 类实现了 <code>__iter__</code> 和 <code>__next__</code> 方法，可以看成是一个迭代器, 有惰性运算的特性，相对 Python2提升了性能，可以节约内存。</p><hr><h4 id="sorted"><a href="#sorted" class="headerlink" title="sorted()"></a>sorted()</h4><p><code>sorted()</code> 函数对所有可迭代的对象进行排序操作。</p><blockquote><p><strong>sort 与 sorted 区别：</strong></p><ul><li>sort 是应用在 list 上的方法，sorted 可以对所有可迭代的对象进行排序操作。</li><li>list 的 sort 方法返回的是对已经存在的列表进行操作，而内建函数 sorted 方法返回的是一个新的 list，而不是在原来的基础上进行的操作。</li></ul></blockquote><p><code>sorted()</code> 语法：</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># sorted(iterable, key=None, reverse=False)</span></span><br><span class="line"><span class="comment">## 参数 —— iterable -- 可迭代对象； key -- 主要是用来进行比较的元素，只有一个参数，具体的函数的参数就是取自于可迭代对象中，指定可迭代对象中的一个元素来进行排序； reverse -- 排序规则，reverse = True 降序 ， reverse = False 升序（默认）</span></span><br><span class="line"><span class="comment">## 返回值 —— 重新排序的列表</span></span><br><span class="line">&gt;&gt;&gt;sorted([<span class="number">5</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">1</span>, <span class="number">4</span>])</span><br><span class="line">[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 使用集合的sort()方法，实现类似结果</span></span><br><span class="line">&gt;&gt;&gt;a = [<span class="number">5</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">1</span>,<span class="number">4</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a.sort()</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a</span><br><span class="line">[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># sort()及sorted()的区别在于， sort()返回None，排序操作直接作用在原list上，而sorted()排序后会返回新的list</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>a = [<span class="number">1</span>,<span class="number">3</span>,<span class="number">2</span>,<span class="number">4</span>];id(a); a.sort(); id(a)</span><br><span class="line"><span class="number">1734959842440</span></span><br><span class="line"><span class="number">1734959842440</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>b = [<span class="number">4</span>,<span class="number">3</span>,<span class="number">1</span>,<span class="number">2</span>]; id(b);id(sorted(b));</span><br><span class="line"><span class="number">1734959953864</span></span><br><span class="line"><span class="number">1734959953672</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># sort()和sorted() 另一个区别在于list.sort() 方法只为 list 定义。而 sorted() 函数可以接收任何的 iterable。</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>sorted(&#123;<span class="number">1</span>: <span class="string">'D'</span>, <span class="number">2</span>: <span class="string">'B'</span>, <span class="number">3</span>: <span class="string">'B'</span>, <span class="number">4</span>: <span class="string">'E'</span>, <span class="number">5</span>: <span class="string">'A'</span>&#125;)</span><br><span class="line">[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 利用key进行倒序排序</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>example_list = [<span class="number">5</span>, <span class="number">0</span>, <span class="number">6</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">7</span>, <span class="number">3</span>, <span class="number">4</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>result_list = sorted(example_list, key=<span class="keyword">lambda</span> x: x * <span class="number">-1</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>print(result_list)</span><br><span class="line">[<span class="number">7</span>, <span class="number">6</span>, <span class="number">5</span>, <span class="number">4</span>, <span class="number">3</span>, <span class="number">2</span>, <span class="number">1</span>, <span class="number">0</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 进行反向排序，也可传入第三个参数 reverse=True：</span></span><br><span class="line">&gt;&gt;&gt;example_list = [<span class="number">5</span>, <span class="number">0</span>, <span class="number">6</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">7</span>, <span class="number">3</span>, <span class="number">4</span>]</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>sorted(example_list, reverse=<span class="keyword">True</span>)</span><br><span class="line">[<span class="number">7</span>, <span class="number">6</span>, <span class="number">5</span>, <span class="number">4</span>, <span class="number">3</span>, <span class="number">2</span>, <span class="number">1</span>, <span class="number">0</span>]</span><br></pre></td></tr></table></figure><hr><h3 id="返回函数"><a href="#返回函数" class="headerlink" title="返回函数"></a>返回函数</h3><p>高阶函数除了可以接受函数作为参数外，还可以把函数作为结果值返回。</p><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 返回累加函数变量</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">lazy_sum</span><span class="params">(*args)</span>:</span>	<span class="comment"># 外部函数</span></span><br><span class="line">     <span class="function"><span class="keyword">def</span> <span class="title">sum</span><span class="params">()</span>:</span>		<span class="comment">#内部函数 可以引用外部函数lazy_sum的参数和局部变量</span></span><br><span class="line">         ax = <span class="number">0</span></span><br><span class="line">         <span class="keyword">for</span> n <span class="keyword">in</span> args:</span><br><span class="line">             ax = ax + n</span><br><span class="line">         <span class="keyword">return</span> ax</span><br><span class="line">     <span class="keyword">return</span> sum		<span class="comment"># 返回函数变量（返回函数sum时，lazy_sum相关参数和变量都保存在返回的函数中，闭包）</span></span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>f = lazy_sum(<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">9</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>f</span><br><span class="line">&lt;function lazy_sum.&lt;locals&gt;.sum at <span class="number">0x00000193F3C89048</span>&gt;</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>f()		<span class="comment"># 返回的函数并没有立刻执行，而是直到调用了f()才执行</span></span><br><span class="line"><span class="number">25</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 调用lazy_sum()时，每次调用都会返回一个新的函数</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>f1 = lazy_sum(<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">9</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>f2 = lazy_sum(<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">9</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>f1==f2	<span class="comment"># f1()和f2()的调用结果互不影响</span></span><br><span class="line"><span class="keyword">False</span></span><br></pre></td></tr></table></figure><hr><h4 id="闭包"><a href="#闭包" class="headerlink" title="闭包"></a>闭包</h4><p>一个函数返回了一个内部函数，该内部函数引用了外部函数的相关参数和变量，我们把该返回的内部函数称为<strong>闭包（Closure）</strong></p><ul><li>闭包的最大特点就是引用了自由变量，即使生成闭包的环境已经释放，闭包仍然存在。</li><li>闭包在运行时可以有多个实例，即使传入的参数相同。</li></ul><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 调用lazy_sum()时，每次调用都会返回一个新的函数</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>f1 = lazy_sum(<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">9</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>f2 = lazy_sum(<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>, <span class="number">7</span>, <span class="number">9</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>f1 == f2	<span class="comment"># f1()和f2()的调用结果互不影响</span></span><br><span class="line"><span class="keyword">False</span></span><br></pre></td></tr></table></figure><ul><li>利用闭包，还可以模拟类的实例。</li></ul><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 构造一个类，用于求一个点到另一个点的距离：</span></span><br><span class="line"><span class="keyword">from</span> math <span class="keyword">import</span> sqrt</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="class"><span class="keyword">class</span> <span class="title">Point</span><span class="params">(object)</span>:</span></span><br><span class="line">     <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, x, y)</span>:</span></span><br><span class="line">         self.x, self.y = x, y</span><br><span class="line"></span><br><span class="line">     <span class="function"><span class="keyword">def</span> <span class="title">get_distance</span><span class="params">(self, u, v)</span>:</span></span><br><span class="line">         distance = sqrt((self.x - u) ** <span class="number">2</span> + (self.y - v) ** <span class="number">2</span>)</span><br><span class="line">         <span class="keyword">return</span> distance</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>pt = Point(<span class="number">7</span>, <span class="number">2</span>)        <span class="comment"># 创建一个点</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>pt.get_distance(<span class="number">10</span>, <span class="number">6</span>)  <span class="comment"># 求到另一个点的距离</span></span><br><span class="line"><span class="number">5.0</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 用闭包来实现：</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">point</span><span class="params">(x, y)</span>:</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get_distance</span><span class="params">(u, v)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> sqrt((x - u) ** <span class="number">2</span> + (y - v) ** <span class="number">2</span>)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> get_distance</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>pt = point(<span class="number">7</span>, <span class="number">2</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>pt(<span class="number">10</span>, <span class="number">6</span>)</span><br><span class="line"><span class="number">5.0</span></span><br></pre></td></tr></table></figure><blockquote><p><strong>注意：</strong> 尽量避免在闭包中引用循环变量，或者后续会发生变化的变量。</p></blockquote><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">count</span><span class="params">()</span>:</span></span><br><span class="line">    funcs = []</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]:</span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">f</span><span class="params">()</span>:</span></span><br><span class="line">            <span class="keyword">return</span> i</span><br><span class="line">        funcs.append(f)</span><br><span class="line">    <span class="keyword">return</span> funcs</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>f1, f2, f3 = count()</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>f1()</span><br><span class="line"><span class="number">3</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>f2()</span><br><span class="line"><span class="number">3</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>f3()</span><br><span class="line"><span class="number">3</span></span><br><span class="line"><span class="comment"># 原因在于上面的函数 f 引用了变量 i，但函数 f 并非立刻执行，当 for 循环结束时，此时变量 i 的值是3，funcs 里面的函数引用的变量都是 3，最终结果也就全为 3。</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 可以再创建一个函数，并将循环变量的值传给该函数</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">count</span><span class="params">()</span>:</span></span><br><span class="line">    funcs = []</span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]:</span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">g</span><span class="params">(param)</span>:</span></span><br><span class="line">            f = <span class="keyword">lambda</span> : param    <span class="comment"># 这里创建了一个匿名函数</span></span><br><span class="line">            <span class="keyword">return</span> f</span><br><span class="line">        funcs.append(g(i))        <span class="comment"># 将循环变量的值传给 g</span></span><br><span class="line">    <span class="keyword">return</span> funcs</span><br><span class="line"></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>f1, f2, f3 = count()</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>f1()</span><br><span class="line"><span class="number">1</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>f2()</span><br><span class="line"><span class="number">2</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>f3()</span><br><span class="line"><span class="number">3</span></span><br></pre></td></tr></table></figure></div><div><div><div style="text-align:center;color:#ccc;font-size:16px">------ 全文结束 <i class="fa fa-thumbs-up"></i> 感谢您的阅读!!! ------</div></div></div><div><ul class="post-copyright"><li class="post-copyright-author"><strong>本文作者： </strong>Alex.D</li><li class="post-copyright-link"><strong>本文链接：</strong> <a href="https://alex_d.gitee.io/alex.d-blog/posts/736330a0/" title="Python学习笔记 - 函数式编程之高阶函数">https://alex_d.gitee.io/alex.d-blog/posts/736330a0/</a></li><li class="post-copyright-license"><strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <span class="exturl" data-url="aHR0cHM6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL2xpY2Vuc2VzL2J5LW5jLXNhLzQuMC8="><i class="fa fa-fw fa-creative-commons"></i>BY-NC-SA</span> 许可协议。转载请注明出处！</li></ul></div><div><div id="wechat_subscriber" style="display:block;padding:5px 0;margin:10px auto;width:100%;text-align:center"><img id="wechat_subscriber_qcode" src="/alex.d-blog/images/weixingongzhonghao.png" alt="Alex.D wechat" style="width:200px;max-width:100%"><div></div></div></div><div><div style="padding:10px 0;margin:20px auto;width:90%;text-align:center"><div>坚持原创技术分享，您的支持将鼓励我继续创作！</div><button id="rewardButton" disable="enable" onclick="var qr = document.getElementById(&quot;QR&quot;); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}"><span>打赏</span></button><div id="QR" style="display:none"><div id="wechat" style="display:inline-block"><img id="wechat_qr" src="/alex.d-blog/images/wechatpay.jpg" alt="Alex.D 微信支付"><p>微信支付</p></div><div id="alipay" style="display:inline-block"><img id="alipay_qr" src="/alex.d-blog/images/alipay.jpg" alt="Alex.D 支付宝"><p>支付宝</p></div></div></div></div><footer class="post-footer"><div class="post-tags"><a href="/alex.d-blog/tags/Python/" rel="tag"><i class="fa fa-tag"></i> Python</a> <a href="/alex.d-blog/tags/函数式编程/" rel="tag"><i class="fa fa-tag"></i> 函数式编程</a> <a href="/alex.d-blog/tags/高阶函数/" rel="tag"><i class="fa fa-tag"></i> 高阶函数</a> <a href="/alex.d-blog/tags/闭包/" rel="tag"><i class="fa fa-tag"></i> 闭包</a></div><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/alex.d-blog/posts/62e02099/" rel="next" title="Windows小技巧 -- chrome下页面保存的多种姿势"><i class="fa fa-chevron-left"></i> Windows小技巧 -- chrome下页面保存的多种姿势</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"><a href="/alex.d-blog/posts/6b28b742/" rel="prev" title="Selenium Webdriver之Chrome浏览器操作小记">Selenium Webdriver之Chrome浏览器操作小记 <i class="fa fa-chevron-right"></i></a></div></div></footer></div></article></div></div><div class="comments" id="comments"></div></div><div class="sidebar-toggle"><div class="sidebar-toggle-line-wrap"><span class="sidebar-toggle-line sidebar-toggle-line-first"></span> <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span> <span class="sidebar-toggle-line sidebar-toggle-line-last"></span></div></div><aside id="sidebar" class="sidebar"><div id="sidebar-dimmer"></div><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">文章目录</li><li class="sidebar-nav-overview" data-target="site-overview-wrap">站点概览</li></ul><div class="site-overview-wrap sidebar-panel"><div class="site-overview"><div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"><img class="site-author-image" itemprop="image" src="/alex.d-blog/images/avatar.jpg" alt="Alex.D"><p class="site-author-name" itemprop="name">Alex.D</p><p class="site-description motion-element" itemprop="description">Alex.D 个人博客，记录和分享工作经验、学习心得等</p></div><nav class="site-state motion-element"><div class="site-state-item site-state-posts"><a href="/alex.d-blog/archives/"><span class="site-state-item-count">32</span> <span class="site-state-item-name">日志</span></a></div><div class="site-state-item site-state-categories"><a href="/alex.d-blog/categories/index.html"><span class="site-state-item-count">19</span> <span class="site-state-item-name">分类</span></a></div><div class="site-state-item site-state-tags"><a href="/alex.d-blog/tags/index.html"><span class="site-state-item-count">49</span> <span class="site-state-item-name">标签</span></a></div></nav><div class="feed-link motion-element"><a href="/alex.d-blog/rss.xml" rel="alternate"><i class="fa fa-rss"></i> RSS</a></div><div class="links-of-author motion-element"><span class="links-of-author-item"><span class="exturl" data-url="aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTI5OTU5NjQ=" title="CSDN &rarr; https://blog.csdn.net/u012995964"><i class="fa fa-fw fa-link"></i>CSDN</span> </span><span class="links-of-author-item"><span class="exturl" data-url="aHR0cHM6Ly93d3cuamlhbnNodS5jb20vdS8wNTlmNmYzZTU3OTE=" title="简书 &rarr; https://www.jianshu.com/u/059f6f3e5791"><i class="fa fa-fw fa-link"></i>简书</span> </span><span class="links-of-author-item"><span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL2FueWVy" title="GitHub &rarr; https://github.com/anyer"><i class="fa fa-fw fa-github"></i>GitHub</span> </span><span class="links-of-author-item"><span class="exturl" data-url="aHR0cHM6Ly9naXRlZS5jb20vYWxleF9k" title="Gitee &rarr; https://gitee.com/alex_d"><i class="fa fa-fw fa-link"></i>Gitee</span> </span><span class="links-of-author-item"><span class="exturl" data-url="bWFpbHRvOm1hcGxlXzYzOTJAMTYzLmNvbQ==" title="E-Mail &rarr; mailto:maple_6392@163.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</span></span></div><div class="cc-license motion-element" itemprop="license"><span class="exturl cc-opacity" data-url="aHR0cHM6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL2xpY2Vuc2VzL2J5LW5jLXNhLzQuMC8="><img src="/alex.d-blog/images/cc-by-nc-sa.svg" alt="Creative Commons"></span></div><div class="links-of-blogroll motion-element links-of-blogroll-inline"><div class="links-of-blogroll-title"><i class="fa fa-fw fa-link"></i> Links - 友情链接</div><ul class="links-of-blogroll-list"><li class="links-of-blogroll-item"><span class="exturl" data-url="aHR0cHM6Ly95dWFud2UuZ2l0aHViLmlvLw==" title="https://yuanwe.github.io/">Yuanwe</span></li></ul></div></div></div><div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#函数式编程"><span class="nav-number">1.</span> <span class="nav-text">函数式编程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#高阶函数"><span class="nav-number">1.1.</span> <span class="nav-text">高阶函数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#map"><span class="nav-number">1.1.1.</span> <span class="nav-text">map()</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#reduce"><span class="nav-number">1.1.2.</span> <span class="nav-text">reduce()</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#filter"><span class="nav-number">1.1.3.</span> <span class="nav-text">filter()</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#sorted"><span class="nav-number">1.1.4.</span> <span class="nav-text">sorted()</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#返回函数"><span class="nav-number">1.2.</span> <span class="nav-text">返回函数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#闭包"><span class="nav-number">1.2.1.</span> <span class="nav-text">闭包</span></a></li></ol></li></ol></li></ol></div></div></div></div></aside></div></main><footer id="footer" class="footer"><div class="footer-inner"><div class="copyright">&copy; 2015 – <span itemprop="copyrightYear">2019</span> <span class="with-love" id="animate"><i class="fa fa-heartbeat"></i> </span><span class="author" itemprop="copyrightHolder">Alex.D</span> <span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-area-chart"></i> </span><span title="站点总字数">97k</span> <span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-coffee"></i> </span><span title="站点阅读时长">1:28</span></div><div class="powered-by">由 <span class="exturl theme-link" data-url="aHR0cHM6Ly9oZXhvLmlv">Hexo</span> 强力驱动 v3.8.0</div><span class="post-meta-divider">|</span><div class="theme-info">主题 – <span class="exturl theme-link" data-url="aHR0cHM6Ly90aGVtZS1uZXh0Lm9yZw==">NexT.Mist</span> v7.0.0</div><div class="busuanzi-count"><script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span class="post-meta-item-icon"><i class="fa fa-user"></i> </span><span class="site-uv" title="总访客量"><span class="busuanzi-value" id="busuanzi_value_site_uv"></span> </span><span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-eye"></i> </span><span class="site-pv" title="总访问量"><span class="busuanzi-value" id="busuanzi_value_site_pv"></span></span></div></div></footer><div class="back-to-top"><i class="fa fa-arrow-up"></i> <span id="scrollpercent"><span>0</span>%</span></div><div><div class="addthis_inline_share_toolbox"><script src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5b1f1cb368ef81fb" async></script></div></div></div><script>"[object Function]"!==Object.prototype.toString.call(window.Promise)&&(window.Promise=null)</script><script color="0,0,255" opacity="0.3" zindex="-1" count="99" src="//cdn.jsdelivr.net/gh/theme-next/theme-next-canvas-nest@1/canvas-nest.min.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/velocity/1.2.1/velocity.min.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/velocity/1.2.1/velocity.ui.min.js"></script><script src="//cdn.jsdelivr.net/gh/theme-next/theme-next-three@1/three.min.js"></script><script src="//cdn.jsdelivr.net/gh/theme-next/theme-next-three@1/three-waves.min.js"></script><script src="/alex.d-blog/js/src/utils.js?v=7.0.0"></script><script src="/alex.d-blog/js/src/motion.js?v=7.0.0"></script><script src="/alex.d-blog/js/src/schemes/muse.js?v=7.0.0"></script><script src="/alex.d-blog/js/src/scrollspy.js?v=7.0.0"></script><script src="/alex.d-blog/js/src/post-details.js?v=7.0.0"></script><script src="/alex.d-blog/js/src/bootstrap.js?v=7.0.0"></script><script src="//cdn.jsdelivr.net/npm/leancloud-storage@3/dist/av-min.js"></script><script src="//cdnjs.cloudflare.com/ajax/libs/valine/1.3.4/Valine.min.js"></script><script>var GUEST=["nick","mail","link"],guest="nick,mail,link";guest=guest.split(",").filter(function(e){return GUEST.indexOf(e)>-1}),new Valine({el:"#comments",verify:!1,notify:!1,appId:"bMq5EYdO7g53KqEdWTWkVm7I-gzGzoHsz",appKey:"BVg4Pry8PJsDq6i9g8Iydm5M",placeholder:"Just go go",avatar:"mm",meta:guest,pageSize:"10",visitor:!1})</script><script>function proceedsearch(){$("body").append('<div class="search-popup-overlay local-search-pop-overlay"></div>').css("overflow","hidden"),$(".search-popup-overlay").click(onPopupClose),$(".popup").toggle();var e=$("#local-search-input");e.attr("autocapitalize","none"),e.attr("autocorrect","off"),e.focus()}var isfetched=!1,isXml=!0,search_path="search.xml";0===search_path.length?search_path="search.xml":/json$/i.test(search_path)&&(isXml=!1);var path="/alex.d-blog/"+search_path,onPopupClose=function(e){$(".popup").hide(),$("#local-search-input").val(""),$(".search-result-list").remove(),$("#no-result").remove(),$(".local-search-pop-overlay").remove(),$("body").css("overflow","")},searchFunc=function(e,t,o){"use strict";$("body").append('<div class="search-popup-overlay local-search-pop-overlay"><div id="search-loading-icon"><i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i></div></div>').css("overflow","hidden"),$("#search-loading-icon").css("margin","20% auto 0 auto").css("text-align","center"),$.ajax({url:e,dataType:isXml?"xml":"json",async:!0,success:function(e){isfetched=!0,$(".popup").detach().appendTo(".header-inner");var n=isXml?$("entry",e).map(function(){return{title:$("title",this).text(),content:$("content",this).text(),url:$("url",this).text()}}).get():e,r=document.getElementById(t),s=document.getElementById(o),a=function(){var e=r.value.trim().toLowerCase(),t=e.split(/[\s\-]+/);t.length>1&&t.push(e);var o=[];if(e.length>0&&n.forEach(function(n){function r(t,o,n,r){for(var s=r[r.length-1],a=s.position,i=s.word,l=[],h=0;a+i.length<=n&&0!=r.length;){i===e&&h++,l.push({position:a,length:i.length});var p=a+i.length;for(r.pop();0!=r.length&&(s=r[r.length-1],a=s.position,i=s.word,p>a);)r.pop()}return c+=h,{hits:l,start:o,end:n,searchTextCount:h}}function s(e,t){var o="",n=t.start;return t.hits.forEach(function(t){o+=e.substring(n,t.position);var r=t.position+t.length;o+='<b class="search-keyword">'+e.substring(t.position,r)+"</b>",n=r}),o+=e.substring(n,t.end)}var a=!1,i=0,c=0,l=n.title.trim(),h=l.toLowerCase(),p=n.content.trim().replace(/<[^>]+>/g,""),u=p.toLowerCase(),f=decodeURIComponent(n.url).replace(/\/{2,}/g,"/"),d=[],g=[];if(""!=l&&(t.forEach(function(e){function t(e,t,o){var n=e.length;if(0===n)return[];var r=0,s=[],a=[];for(o||(t=t.toLowerCase(),e=e.toLowerCase());(s=t.indexOf(e,r))>-1;)a.push({position:s,word:e}),r=s+n;return a}d=d.concat(t(e,h,!1)),g=g.concat(t(e,u,!1))}),(d.length>0||g.length>0)&&(a=!0,i=d.length+g.length)),a){[d,g].forEach(function(e){e.sort(function(e,t){return t.position!==e.position?t.position-e.position:e.word.length-t.word.length})});var v=[];0!=d.length&&v.push(r(l,0,l.length,d));for(var $=[];0!=g.length;){var C=g[g.length-1],m=C.position,x=C.word,w=m-20,y=m+80;0>w&&(w=0),y<m+x.length&&(y=m+x.length),y>p.length&&(y=p.length),$.push(r(p,w,y,g))}$.sort(function(e,t){return e.searchTextCount!==t.searchTextCount?t.searchTextCount-e.searchTextCount:e.hits.length!==t.hits.length?t.hits.length-e.hits.length:e.start-t.start});var T=parseInt("1");T>=0&&($=$.slice(0,T));var b="";b+=0!=v.length?"<li><a href='"+f+"' class='search-result-title'>"+s(l,v[0])+"</a>":"<li><a href='"+f+"' class='search-result-title'>"+l+"</a>",$.forEach(function(e){b+="<a href='"+f+'\'><p class="search-result">'+s(p,e)+"...</p></a>"}),b+="</li>",o.push({item:b,searchTextCount:c,hitCount:i,id:o.length})}}),1===t.length&&""===t[0])s.innerHTML='<div id="no-result"><i class="fa fa-search fa-5x"></i></div>';else if(0===o.length)s.innerHTML='<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>';else{o.sort(function(e,t){return e.searchTextCount!==t.searchTextCount?t.searchTextCount-e.searchTextCount:e.hitCount!==t.hitCount?t.hitCount-e.hitCount:t.id-e.id});var a='<ul class="search-result-list">';o.forEach(function(e){a+=e.item}),a+="</ul>",s.innerHTML=a}};r.addEventListener("input",a),$(".local-search-pop-overlay").remove(),$("body").css("overflow",""),proceedsearch()}})};$(".popup-trigger").click(function(e){e.stopPropagation(),isfetched===!1?searchFunc(path,"local-search-input","local-search-result"):proceedsearch()}),$(".popup-btn-close").click(onPopupClose),$(".popup").click(function(e){e.stopPropagation()}),$(document).on("keyup",function(e){var t=27===e.which&&$(".search-popup").is(":visible");t&&onPopupClose()})</script><script>function addCount(Counter) {
      var $visitors = $('.leancloud_visitors');
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', '/classes/Counter/' + counter.objectId, JSON.stringify({ time: { '__op': 'Increment', 'amount': 1 } }))
            
              .done(function() {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.time + 1);
              })
            
              .fail(function ({ responseJSON }) {
                console.log(`Failed to save Visitor num, with error message: ${responseJSON.error}`);
              })
          } else {
            
              var $element = $(document.getElementById(url));
              $element.find('.leancloud-visitors-count').text('Counter not initialized! More info at console err msg.');
              console.error('ATTENTION! LeanCloud counter has security bug, see how to solve it here: https://github.com/theme-next/hexo-leancloud-counter-security. \n However, you can still use LeanCloud without security, by setting `security` option to `false`.');
            
          }
        })
        .fail(function ({ responseJSON }) {
          console.log(`LeanCloud Counter Error: ${responseJSON.code} ${responseJSON.error}`);
        });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + 'bMq5EYdO7g53KqEdWTWkVm7I-gzGzoHsz')
        .done(function({ api_server }) {
          var Counter = function(method, url, data) {
            return $.ajax({
              method: method,
              url: 'https://' + api_server + '/1.1' + url,
              headers: {
                'X-LC-Id': 'bMq5EYdO7g53KqEdWTWkVm7I-gzGzoHsz',
                'X-LC-Key': 'BVg4Pry8PJsDq6i9g8Iydm5M',
                'Content-Type': 'application/json',
              },
              data: data
            });
          };
          
            addCount(Counter);
          
        });
    });</script><script>!function(){var t=document.createElement("script"),s=window.location.protocol.split(":")[0];"https"===s?t.src="https://zz.bdstatic.com/linksubmit/push.js":t.src="http://push.zhanzhang.baidu.com/push.js";var e=document.getElementsByTagName("script")[0];e.parentNode.insertBefore(t,e)}()</script><script src="/alex.d-blog/js/src/js.cookie.js?v=7.0.0"></script><script src="/alex.d-blog/js/src/scroll-cookie.js?v=7.0.0"></script><script src="/alex.d-blog/js/src/exturl.js?v=7.0.0"></script><style>.copy-btn{display:inline-block;padding:6px 12px;font-size:13px;font-weight:700;line-height:20px;color:#333;white-space:nowrap;vertical-align:middle;cursor:pointer;background-color:#eee;background-image:linear-gradient(#fcfcfc,#eee);border:1px solid #d5d5d5;border-radius:3px;user-select:none;outline:0}.highlight-wrap .copy-btn{transition:opacity .3s ease-in-out;opacity:0;padding:2px 6px;position:absolute;right:4px;top:8px}.highlight-wrap .copy-btn:focus,.highlight-wrap:hover .copy-btn{opacity:1}.highlight-wrap{position:relative}</style><script>$(".highlight").each(function(e,t){var n=$("<div>").addClass("highlight-wrap");$(t).after(n),n.append($("<button>").addClass("copy-btn").append("复制").on("click",function(e){var t=$(this).parent().find(".code").find(".line").map(function(e,t){return $(t).text()}).toArray().join("\n"),n=document.createElement("textarea"),o=document.createRange(),a=window.getSelection(),i=window.pageYOffset||document.documentElement.scrollTop;n.style.top=i+"px",n.style.position="absolute",n.style.opacity="0",n.value=t,n.textContent=t,n.contentEditable=!0,n.readOnly=!1,document.body.appendChild(n),o.selectNode(n),a.removeAllRanges(),a.addRange(o),n.setSelectionRange(0,t.length);var d=document.execCommand("copy");d?$(this).text("复制成功"):$(this).text("复制失败"),n.blur(),$(this).blur()})).on("mouseleave",function(e){var t=$(this).find(".copy-btn");setTimeout(function(){t.text("复制")},300)}).append(t)})</script><script type="text/javascript" src="/alex.d-blog/js/src/love.js"></script></body></html><!-- rebuild by neat -->